package com.music.note_android.ui.editor

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.activity.viewModels
import com.music.note_android.R
import dagger.hilt.android.AndroidEntryPoint
import com.music.note_android.databinding.ActivityCanvasEditorBinding
import com.music.note_android.data.model.Note
import com.music.note_android.ui.editor.Stroke
import com.music.note_android.ui.editor.DrawingToolbar

@AndroidEntryPoint
class CanvasEditorActivity : AppCompatActivity(), DrawingToolbar.OnToolbarActionListener {

    private lateinit var binding: ActivityCanvasEditorBinding
    private lateinit var viewModel: CanvasEditorViewModel
    private var noteId: String = ""
    private var isFullscreen = false
    private var isSideToolPanelVisible = false

    companion object {
        private const val EXTRA_NOTE_ID = "extra_note_id"
        private const val EXTRA_NOTE_TITLE = "extra_note_title"

        fun newIntent(context: Context, noteId: String, noteTitle: String? = null): Intent {
            return Intent(context, CanvasEditorActivity::class.java).apply {
                putExtra(EXTRA_NOTE_ID, noteId)
                noteTitle?.let { putExtra(EXTRA_NOTE_TITLE, it) }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCanvasEditorBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 获取传入的笔记ID
        noteId = intent.getStringExtra(EXTRA_NOTE_ID) ?: ""
        val noteTitle = intent.getStringExtra(EXTRA_NOTE_TITLE)

        // 设置工具栏
        setSupportActionBar(binding.toolbar)
        supportActionBar?.apply {
            setDisplayHomeAsUpEnabled(true)
            title = noteTitle ?: getString(R.string.canvas_editor_title)
        }

        // 初始化ViewModel
        viewModel = viewModels<CanvasEditorViewModel>().value

        // 设置绘图工具栏监听器
        binding.drawingToolbar.setOnToolbarActionListener(this)

        // 设置画布监听器
        setupCanvasListeners()

        // 设置UI监听器
        setupUIListeners()

        // 观察ViewModel状态
        observeViewModel()

        // 加载笔记数据
        if (noteId.isNotEmpty()) {
            viewModel.loadNote(noteId)
        }
    }

    private fun setupCanvasListeners() {
        binding.drawingCanvas.apply {
            // 设置画布状态监听器
            setOnCanvasStateChangeListener(object : DrawingCanvasView.OnCanvasStateChangeListener {
                override fun onZoomChanged(zoomLevel: Float) {
                    binding.tvZoomLevel.text = "${(zoomLevel * 100).toInt()}%"
                }

                override fun onPositionChanged(x: Float, y: Float) {
                    binding.tvCanvasPosition.text = "(${x.toInt()}, ${y.toInt()})"
                }

                override fun onStrokeAdded(stroke: Stroke) {
                    viewModel.markAsModified()
                }

                override fun onStrokeRemoved(stroke: Stroke) {
                    viewModel.markAsModified()
                }

                override fun onCanvasCleared() {
                    viewModel.markAsModified()
                }
            })

            // 设置压感监听器
            setOnPressureChangeListener { pressure ->
                // 可以在这里显示压感信息
            }
        }
    }

    private fun setupUIListeners() {
        // 浮动操作按钮
        binding.fabMenu.setOnClickListener {
            toggleSideToolPanel()
        }

        // 侧边工具面板按钮
        binding.btnLayers.setOnClickListener {
            // TODO: 实现图层功能
            Toast.makeText(this, "图层功能开发中", Toast.LENGTH_SHORT).show()
        }

        binding.btnGrid.setOnClickListener {
            toggleGrid()
        }

        binding.btnRuler.setOnClickListener {
            toggleRuler()
        }

        binding.btnFullscreen.setOnClickListener {
            toggleFullscreen()
        }
    }

    private fun observeViewModel() {
        viewModel.note.observe(this) { note ->
            note?.let {
                supportActionBar?.title = it.title
                // 加载画布数据
                loadCanvasData(it)
            }
        }

        viewModel.isLoading.observe(this) { isLoading ->
            binding.loadingIndicator.visibility = if (isLoading) View.VISIBLE else View.GONE
        }

        viewModel.error.observe(this) { error ->
            error?.let {
                Toast.makeText(this, it, Toast.LENGTH_LONG).show()
            }
        }

        viewModel.isSaved.observe(this) { isSaved ->
            if (isSaved) {
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun loadCanvasData(note: Note) {
        // TODO: 从笔记数据中加载画布内容
        // 这里需要实现画布数据的序列化和反序列化
    }

    private fun toggleSideToolPanel() {
        isSideToolPanelVisible = !isSideToolPanelVisible
        binding.sideToolPanel.visibility = if (isSideToolPanelVisible) View.VISIBLE else View.GONE
        
        // 旋转FAB图标
        val rotation = if (isSideToolPanelVisible) 45f else 0f
        binding.fabMenu.animate().rotation(rotation).setDuration(200).start()
    }

    private fun toggleGrid() {
        val showGrid = !binding.drawingCanvas.isGridVisible()
        binding.drawingCanvas.setGridVisible(showGrid)
        binding.btnGrid.isSelected = showGrid
    }

    private fun toggleRuler() {
        val showRuler = !binding.drawingCanvas.isRulerVisible()
        binding.drawingCanvas.setRulerVisible(showRuler)
        binding.btnRuler.isSelected = showRuler
    }

    private fun toggleFullscreen() {
        isFullscreen = !isFullscreen
        
        if (isFullscreen) {
            // 进入全屏模式
            supportActionBar?.hide()
            binding.drawingToolbar.visibility = View.GONE
            binding.sideToolPanel.visibility = View.GONE
            binding.canvasInfoPanel.visibility = View.VISIBLE
            
            // 隐藏系统UI
            window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            )
        } else {
            // 退出全屏模式
            supportActionBar?.show()
            binding.drawingToolbar.visibility = View.VISIBLE
            binding.canvasInfoPanel.visibility = View.GONE
            
            // 显示系统UI
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
        }
        
        binding.btnFullscreen.isSelected = isFullscreen
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_canvas_editor, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                onBackPressed()
                true
            }
            R.id.action_save -> {
                saveCanvas()
                true
            }
            R.id.action_export -> {
                exportCanvas()
                true
            }
            R.id.action_settings -> {
                openSettings()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    // DrawingToolbar.OnToolbarActionListener 实现
    override fun onToolSelected(tool: DrawingTool) {
        binding.drawingCanvas.setCurrentTool(tool)
    }

    override fun onColorSelected(color: Int) {
        binding.drawingCanvas.setCurrentColor(color)
    }

    override fun onStrokeWidthChanged(width: Float) {
        binding.drawingCanvas.setStrokeWidth(width)
    }

    override fun onUndoRequested() {
        binding.drawingCanvas.undo()
    }

    override fun onRedoRequested() {
        binding.drawingCanvas.redo()
    }

    override fun onClearRequested() {
        binding.drawingCanvas.clearCanvas()
    }

    private fun saveCanvas() {
        // TODO: 实现画布保存逻辑
        val canvasData = binding.drawingCanvas.getCanvasData()
        viewModel.saveCanvas(noteId, canvasData)
    }

    private fun exportCanvas() {
        // TODO: 实现画布导出功能
        Toast.makeText(this, "导出功能开发中", Toast.LENGTH_SHORT).show()
    }

    private fun openSettings() {
        // TODO: 打开画布设置页面
        Toast.makeText(this, "设置功能开发中", Toast.LENGTH_SHORT).show()
    }

    override fun onBackPressed() {
        if (isFullscreen) {
            toggleFullscreen()
            return
        }
        
        if (isSideToolPanelVisible) {
            toggleSideToolPanel()
            return
        }
        
        // 检查是否有未保存的更改
        if (viewModel.hasUnsavedChanges()) {
            // TODO: 显示保存确认对话框
        }
        
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
        // 自动保存
        if (viewModel.hasUnsavedChanges()) {
            saveCanvas()
        }
    }
}